package com.itheima.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.Category;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.result.Result;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询分类
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageInfo<Category> findByPage(int pageNum, int pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        keyword = (keyword != null ? keyword.trim() : keyword);
        List<Category> list = categoryMapper.findByPage(keyword);
        return new PageInfo<>(list);
    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    @Override
    public Category findById(Integer id) {
        return categoryMapper.findById(id);
    }

    /**
     * 新增分类
     *
     * @param category
     */
    @Override
    public void save(Category category) {
        categoryMapper.save(category);
    }

    /**
     * 查询所有分类
     *
     * @return
     */
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    /**
     * 修改分类
     *
     * @param category
     */
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    /**
     * 删除分类
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        // 检查分类下是否有电影
        if (categoryMapper.hasMovies(Collections.singletonList(id))) {
            throw new BusinessException("该分类下有影视，不能删除");
        }

        categoryMapper.deleteById(id);
    }

    /**
     * 批量删除分类
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        if (!ArrayUtil.isNotEmpty(ids)) {
            throw new BusinessException("请传入要删除的分类id");
        }

        // 检查分类下是否有电影
        if (categoryMapper.hasMovies(ids)) {
            throw new BusinessException("该分类下有影视，不能删除");
        }

        categoryMapper.deleteByIds(ids);

    }
}
